package com.laker.admin.module.excel.application.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.laker.admin.module.excel.application.ExcelFillApplication;
import com.laker.admin.module.excel.domain.ExcelFill;
import com.laker.admin.module.excel.repository.ExcelFillRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;


/**
 * @author : nihongxin
 * @date : 2021/3/22
 */
@Component
public class ExcelFillApplicationImpl implements ExcelFillApplication {

    @Autowired
    private ExcelFillRepository excelFillRepository;

    @Override
    public ExcelFill save(ExcelFill excelFill) {
        return excelFillRepository.save(excelFill);
    }

    @Override
    public void deleteById(Long id) {
        excelFillRepository.deleteById(id);
    }

    @Override
    public ExcelFill getById(Long id) {
        return excelFillRepository.getOne(id);
    }

    @Override
    public Page<ExcelFill> listExcelFillPage(String keyword, Integer pageNo, Integer pageSize) {
        PageRequest page = PageRequest.of(pageNo - 1, pageSize);
        return excelFillRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
            Predicate conjunction = criteriaBuilder.conjunction();
            conjunction.getExpressions().add(criteriaBuilder.equal(root.get("createBy"), StpUtil.getLoginIdAsLong()));
            if (!StringUtils.isEmpty(keyword)) {
                conjunction.getExpressions().add(criteriaBuilder.or(criteriaBuilder.like(root.get("excelTemplateName"), "%" + keyword + "%"),
                        criteriaBuilder.like(root.get("excelFillName"), "%" + keyword + "%")));
            }
            return conjunction;
        }, page);
    }
}
